package com.thinvent.smart.chain.common;

import com.alipay.mychain.sdk.api.MychainClient;
import com.alipay.mychain.sdk.crypto.keypair.Keypair;
import com.alipay.mychain.sdk.domain.account.Identity;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;


@Component
public class ChainSdk {
//    Map<String, MychainClient> sdk = new HashMap<>();
//    Map<String, Keypair> keypairMap = new HashMap<>();
//    Map<String, Identity> identityMap = new HashMap<>();
    public ConcurrentHashMapLocalCacheUtil cache = new ConcurrentHashMapLocalCacheUtil();
    @Cacheable
    public synchronized boolean init(String account,String userPassword){
        if(cache.get("sdk"+account+"_"+userPassword) != null){
            return true;
        }
        return initSdk(account,userPassword);
    }

    private synchronized boolean initSdk(String account, String userPassword) {
        if(cache.get("sdk"+account+"_"+userPassword) != null){
            return true;
        }
        MychainClient mychainClient = new MychainClient();
        ChainEnv chainEnv = new ChainEnv();
        chainEnv.initMychainEnv(account,userPassword);
        boolean init = mychainClient.init(chainEnv.getBuild());
        if (!init) {
            throw new RuntimeException("sdk init failed.");
        }
        cache.put("sdk"+account+"_"+userPassword,mychainClient);
        cache.put("identity"+account+"_"+userPassword,chainEnv.getUserIdentity());
        cache.put("keypair"+account+"_"+userPassword,chainEnv.getUserKeypair());
        return true;
    }

    public MychainClient getSdk(String account,String userPassword) {
        MychainClient mychainClient = (MychainClient) cache.get("sdk"+account+"_"+userPassword);
        return mychainClient;
    }

    public Identity getUserIdentity(String account,String userPassword) {
        Identity identity = (Identity) cache.get("identity"+account+"_"+userPassword);
        return identity;
    }

    public Keypair getUserKeypair(String account,String userPassword) {
        Keypair keypair = (Keypair) cache.get("keypair"+account+"_"+userPassword);
        return keypair;
    }
}
